package console

import (
	"duoke/utils/download"
	"duoke/utils/gcache"
	"duoke/utils/gconv"
	"duoke/utils/gfile"
	"duoke/utils/gtime"
	"duoke/utils/response"
	"duoke/utils/upgrade"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/patrickmn/go-cache"
	"math"
	"os"
)

var Upgrade = new(upgradeCtl)

type upgradeCtl struct{}

// 授权查询
func (ctl *upgradeCtl) Authorize(c *gin.Context) {
	result, err := upgrade.GetVersionList()
	if result == nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{"curr_version": upgrade.Version, "list": result})
}

// 升级查询
func (ctl *upgradeCtl) Upgrade(c *gin.Context) {
	var progress int64
	var cacheKey string = c.ClientIP() + "_download_progress"
	gcache.MemoryCache.Set(cacheKey, progress, cache.DefaultExpiration)
	// redislib.Redis.Do("Set", cacheKey, progress)
	// redislib.Redis.Do("expire", cacheKey, 300)
	if !gfile.Exists("./tmp/") {
		_ = gfile.MakeDir("./tmp/")
	}
	err := download.DownloadFile(upgrade.GetDownUrl(), "./tmp/upgrade.zip", func(length, downLen int64) {
		progress := math.Ceil(float64(downLen) / float64(length) * 100)
		// redislib.Redis.Do("Set", cacheKey, progress)
		gcache.MemoryCache.Set(cacheKey, progress, cache.DefaultExpiration)
	})
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 删除原main文件
	err = os.Rename("./main", "./main"+"_old_"+gtime.Date(10))
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 解压文件
	err = gfile.Unzip("./tmp/upgrade.zip", "./")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 删除下载包
	err = os.Remove("./tmp/upgrade.zip")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	err = os.Chmod("./main", 0755)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "升级成功，请手动重启应用", gin.H{"progress": progress})
}

// 查询下载进度
func (ctl *upgradeCtl) Progress(c *gin.Context) {
	var cacheKey string = c.ClientIP() + "_download_progress"
	progress, _ := gcache.MemoryCache.Get(cacheKey)
	response.Success(c, "success", gin.H{"progress": gconv.Int64(progress)})
}

// 系统重启
func (ctl *upgradeCtl) Reboot(c *gin.Context) {
	go func() {
		panic("主动退出")
	}()
	fmt.Println(os.Getpid())
}
